<?php
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'log.php';

//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

//打印输出数组信息
function printf_info($data)
{
    foreach($data as $key=>$value){
        echo "<font color='#00ff55;'>$key</font> : $value <br/>";
    }
}

//①、获取用户openid
$tools = new JsApiPay();
$openId = $tools->GetOpenid();

//②、统一下单
$Out_trade_no=WxPayConfig::MCHID.date("YmdHis");
$input = new WxPayUnifiedOrder();
$input->SetBody("网演中国1元看大戏抢票");
$input->SetAttach("网演中国1元看大戏抢票");
$input->SetOut_trade_no($Out_trade_no);
$input->SetTotal_fee("100");
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("网演中国1元看大戏抢票");
//$input->SetNotify_url("http://wx.wycn.com/weixinpaytest/example/notify.php");
$input->SetNotify_url("http://wx.wycn.com/weixinpay/example/callback.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($openId);
$order = WxPayApi::unifiedOrder($input);

include("../include/config.inc.php");

//判断是否预约
$sql1="select cid,piaobie,mobile from ".tablePrefix."order where openid='$openId' and total_fee='1' and status='SUCCESS' and transaction_id<>'' and endtime<>'' order by id desc limit 0,1";
$result1=$db->query($sql1);
$row=$db->fetch_array($result1);
$cid = $row["cid"];
$piaobie = $row["piaobie"];
$mobile = $row["mobile"];
$time=date("Y-m-d H:i:s",time());

//判断是否已经抢票
$sql2="select * from ".tablePrefix."dingdian where openid='$openId' and mobile='$mobile' and cid='$cid' and piaobie='$piaobie' and status='SUCCESS' and transaction_id<>'' and endtime<>''";
$result2=$db->query($sql2);
$num_rows2 = mysql_num_rows($result2);
if($num_rows2>=1){
	echo "<script type='text/javascript'>alert('您已经抢到一张“".GetValueByKey(tablePrefix."changci","id",$cid,"title").GetValueByKey(tablePrefix."piaobie","id",$piaobie,"piaobie")."”的票，每个用户限选一个场次、一个票别。');location.href='http://wx.wycn.com/1ykdx/';</script>";
	exit;
}

$sql3="select * from ".tablePrefix."dingdian where cid='$cid' and piaobie='$piaobie' and status='SUCCESS' and transaction_id<>'' and endtime<>''";
$result3=$db->query($sql3);
$num_rows = mysql_num_rows($result3);

if($piaobie==3){
	if($num_rows>=20){
	echo "<script type='text/javascript'>alert('您预约的场次和票别已经被抢完了！');location.href='http://wx.wycn.com/1ykdx/';</script>";
	exit;
	}
	else{
	$sql="insert into ".tablePrefix."dingdian(openid,trade_no,cid,piaobie,mobile,ip,createtime,status) values ('$openId','$Out_trade_no','$cid','$piaobie','$mobile','".GetIP()."','$time','未付款')";
	mysql_query("set names utf8");
	$db->query($sql);
	}
}
if($piaobie==2){
	if($num_rows>=10){
	echo "<script type='text/javascript'>alert('您预约的场次和票别已经被抢完了！');location.href='http://wx.wycn.com/1ykdx/';</script>";
	exit;
	}
	else{
	$sql="insert into ".tablePrefix."dingdian(openid,trade_no,cid,piaobie,mobile,ip,createtime,status) values ('$openId','$Out_trade_no','$cid','$piaobie','$mobile','".GetIP()."','$time','未付款')";
	mysql_query("set names utf8");
	$db->query($sql);
	}
}
if($piaobie==1){
	if($num_rows>=5){
	echo "<script type='text/javascript'>alert('您预约的场次和票别已经被抢完了！');location.href='http://wx.wycn.com/1ykdx/';</script>";
	exit;
	}
	else{
	$sql="insert into ".tablePrefix."dingdian(openid,trade_no,cid,piaobie,mobile,ip,createtime,status) values ('$openId','$Out_trade_no','$cid','$piaobie','$mobile','".GetIP()."','$time','未付款')";
	mysql_query("set names utf8");
	$db->query($sql);
	}
}



//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
//printf_info($order);
$jsApiParameters = $tools->GetJsApiParameters($order);

//获取共享收货地址js函数参数
$editAddress = $tools->GetEditAddressParameters();

//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
/**
 * 注意：
 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
 */
?>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/> 
    <title>网演中国微信支付</title>
	<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			<?php echo $jsApiParameters; ?>,
			function(res){
				WeixinJSBridge.log(res.err_msg);
				//alert(res.err_code+res.err_desc+res.err_msg);
				location.href='http://wx.wycn.com/1ykdx/payok2.php?order_id=<?php echo $Out_trade_no;?>';
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	</script>
	<script type="text/javascript">

	
	window.onload = function(){
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', editAddress, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', editAddress); 
		        document.attachEvent('onWeixinJSBridgeReady', editAddress);
		    }
		}else{
			editAddress();
		}
	};
	
	</script>
	<style type="text/css">
	<!--
	body{margin:0;padding:0;font-size:16px;}
	#orderinfo{margin:0 auto;width:98%;height:200px;overflow:hidden;padding:20px 10px;}
	#orderinfo ul{float:left;width:100%;height:100%;overflow:hidden;margin:0;padding:0;}
	#orderinfo ul li{float:left;width:100%;height:30px;overflow:hidden;}
	#orderinfo ul li em{float:left;width:80px;font-style:normal;text-align:right;}
	-->
	</style>	
</head>
<body>
    <div id="orderinfo">
		<ul>
			<li><em>订单号：</em><?php echo $Out_trade_no;?></li>
			<li><em>名称：</em>网演中国1元看大戏抢票</li>
			<li><em>订单时间：</em><?php echo date("Y-m-d H:i:s");?></li>
			<li><em>支付金额：</em>1.00元</li>
		</ul>
	</div>
	<!--<br/>
    <font color="#9ACD32"><b>该笔订单支付金额为<span style="color:#f00;font-size:50px">1分</span>钱</b></font><br/><br/>-->
	<div align="center">
		<button style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer;  color:white;  font-size:16px;" type="button" onClick="callpay()" >立即支付</button>
	</div>
</body>
</html>